package cn.example.project1.controller;

import cn.example.base.ctrl.BaseCtrl;
import cn.example.configure.CustomerPropertis;
import cn.example.project1.po.Msg;
import cn.example.project1.po.News;
import cn.example.project1.po.Word;
import cn.example.project1.service.MsgService;
import cn.example.project1.service.WordService;
import cn.example.util.enumerate.ResultCode;
import com.alibaba.fastjson.JSON;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.poi.hwpf.HWPFDocument;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 测试
 * Created by WuYubin on 2016/12/8.
 */
@Controller
public class TestCtrl extends BaseCtrl {

    @Resource
    private CustomerPropertis customerPropertis;
    @Resource
    private MsgService msgService;
    @Resource
    private WordService wordService;

    @RequestMapping(value = "index")
    public ModelAndView test() {
        Map<String, Object> cc = new HashMap<>();
        log.info("test propertis:" + customerPropertis.getMessage());
        log.info("test uuid:" + customerPropertis.getUuid());
        ResultCode[] codes = ResultCode.values();
        cc.put("enum", codes);
        return new ModelAndView("test", cc);
    }

    /**
     * 返回码（枚举）
     */
    @GetMapping("result")
    @ResponseBody
    public int enumTest() {
        log.debug("test result code");
        log.info(ResultCode.valueOf("UNIQUE_FAIL").toString());
        log.info(ResultCode.valueOf(-2).toString());
        log.info(ResultCode.valueOf(-5).toString());
        log.info(Enum.valueOf(ResultCode.class, "UNIQUE_FAIL").toString());
        return ResultCode.SUCCESS.value();
    }

    /**
     * 数据库保存word文件DEMO
     */
    @PostMapping("saveWord")
    @ResponseBody
    public int saveWord(@RequestParam String name, @RequestParam MultipartFile word) {
        try {
            Word model = new Word();
            model.setName(name);
            model.setWord(word.getBytes());
            return wordService.save(model);
        } catch (IOException e) {
            log.error("error!", e);
            return 0;
        }
    }

    @GetMapping("getWord")
    public void getWord(HttpServletRequest request, HttpServletResponse response) {
        try {
            byte[] bytes = wordService.getWordByID(3);
            InputStream input = new ByteArrayInputStream(bytes);
            HWPFDocument document = new HWPFDocument(input);
            poiUtil.createDownload(document, "test123.doc", request, response);
        } catch (Exception e) {
            log.error("error!", e);
        }
    }

    /**
     * 文件上传demo
     */
    @PostMapping("upload")
    @ResponseBody
    public String upload(@RequestParam MultipartFile file) {
        String root = "D://FileUpload/";//测试地址
        return uploadUtil.fileUpload(file, root, "demos");
    }

    /**
     * 多文件上传demo
     */
    @PostMapping("uploads")
    @ResponseBody
    public String uploads(@RequestParam List<MultipartFile> files) {
        String root = "D://FileUpload/";//测试地址
        return uploadUtil.fileUpload(files, root, "demos");
    }

    /**
     * 事务demo
     */
    @GetMapping("transactional")
    @ResponseBody
    public int transactional() throws IOException {
        return msgService.insertList(getDemoList()) ? 1 : -1;
    }

    /**
     * 事务demo
     */
    @GetMapping("transactionals")
    @ResponseBody
    public int transactionals() throws IOException {
        return msgService.insertLists(getDemoList()) ? 1 : -1;
    }

    /**
     * 导出Word
     */
    @GetMapping("exportWord")
    public void exportWord(HttpServletRequest request, HttpServletResponse response) {
        String tmpFile = "template.doc";
        News news = new News();
        news.setTitle("标题部份");
        news.setContent("这里是内容，测试使用POI导出到Word的内容！");
        news.setAuthor("MyTest");
        news.setUrl("http://www.zslin.com");
        Map<String, Object> datas = beanUtil.obj2Map(news);
        System.out.println(JSON.toJSONString(datas));
        poiUtil.exportWordDownload(tmpFile, datas, "result.doc", request, response);
    }

    /**
     * 导出Excel
     */
    @GetMapping("exportExcel")
    public void exportExcel(HttpServletResponse response) {
        String[] heads = {"序号", "金额", "描述", "日期"};
        String filename = "测试数据统计表.xls";
        List<List<String>> datas = new ArrayList<>();
        List<String> data = new ArrayList<>();
        data.add("1");
        data.add("123.02");
        data.add("desc");
        data.add(dateUtil.date2Str(new Date(), "yyyy-MM-dd HH:mm:ss"));
        datas.add(data);
//        poiUtil.exportExcelDownload(heads, datas, filename, response);
    }


    private List<Msg> getDemoList() {
        List<Msg> list = new ArrayList<>();
        for (int i = 0; i < 11; i++) {
            Msg msg = new Msg("test" + i, "" + i);
            list.add(msg);
        }
        return list;
    }

}
